package com.config;

import org.apache.ibatis.annotations.Mapper;
import org.jetbrains.annotations.NotNull;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
public class MyBatisSpringConfig {

    public static final String SESSION_FACTORY_BEAN = "sqlSessionFactory";

    @Bean(name = SESSION_FACTORY_BEAN)
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {

        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        factoryBean.setDataSource(dataSource);

        Resource[] resources = getMapperResources();


        factoryBean.setMapperLocations(resources);


        return factoryBean;
    }


    public static Resource[] getMapperResources() {
        // 创建一个 ResourcePatternResolver 实例
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources;
        try {
            resources = resolver.getResources("classpath:com/mapper/*.xml");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return resources;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){

        final MapperScannerConfigurer result = new MapperScannerConfigurer();

        result.setBasePackage("com/mapper");
        //result.setAnnotationClass(Mapper.class);
        result.setSqlSessionFactoryBeanName(SESSION_FACTORY_BEAN);
        return result;
    }


}
